from google.appengine.ext import db
from workitem import workitem

worklists = None #db.GqlQuery('SELECT * FROM worklist')

def addWorklist(new_worklist):
    if exist(new_worklist.name):
        return False
    new_worklist.put()  
    return True

def exist(worklist_name):
    if worklists is not None:
        for x in worklists: 
          if worklist_name == x.name:
            return True
          else:
              continue
        return False
    else:
        return False
    
def removeWorklist(new_worklist):
    '''
    it does not work properly
    '''
    if exist(new_worklist.name):
        worklists.remove(new_worklist)
        return True
    else:
        return False

class worklist(db.Model):

    '''workitems       = [workitem(None,'name1','process','1','flowid')]'''

    name            = db.StringProperty()
    data            = db.StringListProperty()
    assigned_roles  = db.StringListProperty()
    
    
    ''' need extra work for init - joon
    def __init__(self,wl_name,workitems,roles):
        self.name = wl_name
        self.workitems = workitems
        #self.assigned_roles = roles
    '''
    def enqueue(self, workitem):
        workitems.append(workitem)

    def showWorkItems(self, limit, role):
        '''
        it shows the number of workitems that are defined
        '''
        return_item = []
        count = 0
        for item in workitems:
            return_item.append(item)
            count += 1
            if count == limit:
                break
        return return_item            
        
    def dequeue(self):
        return workitem.dequeue()
        '''
        if len(self.workitems) > 0:
        workitem = self.workitems[0]
        self.workitems.remove(0)
        return workitem
        '''
        
    def deleteWorkitem(self, workitemId):
        for i in range(len(self.workitems)):
            if self.workitems[i].getId() == workitemId:
                self.workitems.remove(i)
                break
        return len(self.workitems)

    def addRole(self, role_name):
        if isInRoles(role_name):
            return False
        else:
            assigned_roles.append(role_name)
            return True        
        
    def isInRoles(self, roles):
        for role in roles: 
            if role in self.assigned_roles:
                return True
            else:
                continue
        return False
        
    def removeRole(self, role_name):
        if isInRoles(role_name):
            assigned_roles.remove(role_name)
            return True
        else:
            return False


    def worklistToString():
        s = ''
        for r in worklists:
            if r.name != None:
                s+=(r.name + '; ')
        return s


